package com.lzy.algorithm;

public class 两数相加 {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);

        ListNode l2 = new ListNode(9);
        l2.next = new ListNode(9);
        l2.next.next = new ListNode(6);

        ListNode result = addTwoNumbers(l1, l2);
        while (result != null) {
            System.out.println(result.val);
            result = result.next;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode node = new ListNode(-1);
        ListNode result = node;
        int carry = 0;

        while (l1 != null || l2 != null) {

            int l = 0;
            if (l1 != null) {
                l = l1.val;
                l1 = l1.next;
            }

            int r = 0;
            if (l2 != null) {
                r = l2.val;
                l2 = l2.next;
            }
            // 每一位的数字
            int val = (l + r + carry) % 10;
            // 进位
            carry = (l + r + carry) / 10;

            node.next = new ListNode(val);
            node = node.next;
        }

        // 最后处理进位
        if (carry != 0) {
            node.next = new ListNode(carry);
        }
        return result.next;
    }
}
